<template>
  <div class="message-container" ref="messageContainer">
    <MessageArea title="留言板" :subTitle="`(${data.total})`" :isListLoading="isLoading" :list="data.rows" @submit="handleSubmit" />
  </div>
</template>

<script setup lang="ts">
import * as msgApi from '@/api/message.js'
import mainScroll from '@/composition/useMainScroll'
import { getCurrentInstance, ref, computed, onMounted, onUnmounted, type ComponentPublicInstance } from 'vue'
const proxy: ComponentPublicInstance<any> = getCurrentInstance()?.proxy
const page = ref(1)
const limit = ref(10)
const data = ref({})
const isLoading = ref(true)
onMounted(async () => {
  data.value = await fetchData()
})
async function fetchData() {
  isLoading.value = true
  let result = await msgApi.getMessages(page.value, limit.value)
  isLoading.value = false
  return result
}
//监控容易滚动，注册滚动事件，滚动时派发滚动事件
mainScroll(proxy, 'messageContainer')
const hasMore = computed(() => {
  return data.value.rows.length < data.value.total
})
//滚动加载更多
proxy.$mybus.on('mainScroll', handleScroll)
onUnmounted(() => {
  proxy.$mybus.off('mainScroll', handleScroll)
})
async function handleScroll(dom: any) {
  if (isLoading.value || !dom) {
    // 目前正在加载更多
    return
  }
  const range = 100 // 顶一个可接受的范围，在这个范围内都算达到了底部
  const dec = Math.abs(dom.scrollTop + dom.clientHeight - dom.scrollHeight)
  if (dec <= range) {
    await fetchMore()
  }
}
// 加载下一页
async function fetchMore() {
  if (!hasMore.value) {
    // 没有更多啦
    return
  }
  // isLoading.value = true
  page.value++
  const resp = await fetchData()
  data.value.total = resp.total
  data.value.rows = data.value.rows.concat(resp.rows)
}
//提交留言
async function handleSubmit(formData, callback) {
  const resp = await msgApi.postMessage(formData)
  console.log(resp, '<---resp')
  if (!resp) {
    callback('')
    return
  }
  callback('感谢您的留言')
  data.value.rows.unshift(resp)
  data.value.total++
}
</script>

<style lang="scss" scoped>
.message-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  padding: 35px 0;
  padding-top: 55px;
  box-sizing: border-box;
  scroll-behavior: smooth;
}

.message-area-container {
  width: 80%;
  margin: 0 auto;
}
</style>
